import {
  setToken,
  getToken,
  localSave
} from '@/libs/util'
import api from '@/api/index.js'
import tools from '@/libs/tools.js';
import Cookies from 'js-cookie'

export default {
  state: {
    // userName: 'admin',
    // userId: '1',
    // avatorImgPath: 'https://avatars0.githubusercontent.com/u/20942571?s=460&v=4',
    // token: getToken(),
    // access: ['admin'],
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: true,
    userInfo: {}
  },
  mutations: {
    setAvator(state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    userInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setAccess(state, access) {
      state.access = access
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    },
  },
  actions: {
    // 登录
    handleLogin({
      commit
    }, {
      userName,
      password,
      machineCode
    }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        let params = new FormData()
        params.append('grant_type', 'password')
        params.append('username', userName.trim()) // 用户名
        params.append('password', password.trim()) // 密码
        params.append('scope', 'all')
        api.requestLogin(params).then(data => {
          if (data.code === '1000') {
            commit('setToken', data.data)
            resolve(data.data)
          } else {
            reject(data.message)
          }
        }).catch(err => {
          console.log('登录失败: ' + err)
          reject(err)
        })
      })
    },

    handleChangePwd({
      commit
    }, data) {
      return new Promise((resolve, reject) => {
        try {
          let params = data
          api.changePwd(params, true).then(res => {
            console.log(res)
            if (res.code === '1000') {
              resolve(res.data)
            } else {
              reject(res.message)
            }
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 获取用户相关信息
    getUserInfo({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        console.log("state", state)
        try {
          //获取用户信息
          api.getUserInfo({}, true).then(data => {
            if (data.code == '1000') {

              commit('setAvator', 'https://avatars0.githubusercontent.com/u/20942571?s=460&v=4')
              commit('userInfo', data.data)
              commit('setHasGetInfo', true)
              commit('setAccess', ["admin"])
              commit('setHasGetInfo', true)
              localSave("ls-health-devops-web", JSON.stringify(data.data))
              resolve(data.data)
            } else if (data.code == "9002") {

              // 刷新token
              let token = getToken()
              let loginParams = new FormData()
              loginParams.append('grant_type', 'refresh_token')
              loginParams.append('refresh_token', token.refresh_token)
              api.requestLogin(loginParams).then(data => {
                if (data.code == '1000') {
                  commit('setToken', data.data)
                } else {
                  commit('setToken', '')
                  commit('setAccess', [])
                  commit('setHasGetInfo', false)
                  reject()
                }
              }).catch(err => {
                commit('setToken', '')
                commit('setAccess', [])
                commit('setHasGetInfo', false)
                reject()
              })

            } else if (data.code == "9004") {
              commit('setToken', '')
              commit('setAccess', [])
              commit('setHasGetInfo', false)
              reject(data.data.message)
            } else {
              reject(data.data.message)
            }
          }).catch(err => {
            reject(err)
          });
        } catch (error) {
          // let res = {
          //   data: {
          //     name: 'admin',
          //     user_id: '2',
          //     access: ['admin'],
          //     token: 'admin',
          //     avator: 'https://avatars0.githubusercontent.com/u/20942571?s=460&v=4'
          //   }
          // }
          // const data = res.data
          // commit('setAvator', data.avator)
          // commit('setUserName', data.name)
          // commit('setUserId', data.user_id)
          // commit('setAccess', data.access)
          // commit('setHasGetInfo', true)
          // resolve(data)
          reject(error)
        }
      })
    }
  }
}